package indi.zhifa.study2024.generaltest.logic.shardingTest.consign.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import indi.zhifa.study2024.generaltest.gen.busy.consign.po.GenConsignEntity;
import indi.zhifa.study2024.generaltest.gen.busy.consign.service.IGenConsignDbService;
import indi.zhifa.study2024.generaltest.logic.shardingTest.consign.IConsignService;
import indi.zhifa.study2024.generaltest.logic.shardingTest.consign.entity.request.ConsignAddRequest;
import indi.zhifa.study2024.generaltest.logic.shardingTest.consign.entity.request.ConsignPageRequest;
import indi.zhifa.study2024.generaltest.util.TimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

@RequiredArgsConstructor
@Component
public class ConsignServiceImpl implements IConsignService {

    final IGenConsignDbService mGenConsignDbService;

    @Override
    public GenConsignEntity addConsign(ConsignAddRequest pConsignAddRequest) {

        GenConsignEntity genConsignEntity = new GenConsignEntity();
        genConsignEntity.createInit();
        genConsignEntity.setBillTime(pConsignAddRequest.getBillTime());
        Long billTimeKey = pConsignAddRequest.getBillTime().toEpochSecond(ZoneId.of("Asia/Shanghai").getRules().getOffset(pConsignAddRequest.getBillTime()));
        genConsignEntity.setBillTimeKey(billTimeKey);
        genConsignEntity.setDescription(pConsignAddRequest.getDesc());
        mGenConsignDbService.save(genConsignEntity);
        return genConsignEntity;
    }

    @Override
    public Page<GenConsignEntity> page(ConsignPageRequest pConsignPageRequest) {
        Page<GenConsignEntity> pageReq = new Page<>(pConsignPageRequest.getCurrent(),pConsignPageRequest.getSize());

        Long begTime = TimeUtil.LocalDateTimeToSecond(LocalDate.of(2020,1,1).atTime(0,0,0));
        if(null != pConsignPageRequest.getBegDate()){
            begTime = TimeUtil.LocalDateTimeToSecond(pConsignPageRequest.getBegDate().atTime(0,0,0));
        }
        Long endTime = TimeUtil.LocalDateTimeToSecond(LocalDateTime.now());
        if(null != pConsignPageRequest.getEndDate()){
            endTime = TimeUtil.LocalDateTimeToSecond(pConsignPageRequest.getEndDate().atTime(23,59,59));
        }

        LambdaQueryWrapper<GenConsignEntity> queryWrapper = Wrappers.<GenConsignEntity>lambdaQuery()
                .between(GenConsignEntity::getBillTime,begTime,endTime);

        return mGenConsignDbService.page(pageReq, queryWrapper);
    }
}
